package com.infocollect.project.grant.controller;

import java.io.IOException;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.infocollect.common.exception.CustomException;
import com.infocollect.common.utils.SecurityUtils;
import com.infocollect.common.utils.poi.ExcelCustomUtil;
import com.infocollect.framework.security.LoginUser;
import com.infocollect.project.grant.domain.*;
import com.infocollect.project.grant.service.*;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.runtime.directive.Foreach;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.infocollect.framework.aspectj.lang.annotation.Log;
import com.infocollect.framework.aspectj.lang.enums.BusinessType;
import com.infocollect.framework.web.controller.BaseController;
import com.infocollect.framework.web.domain.AjaxResult;
import com.infocollect.common.utils.poi.ExcelUtil;
import com.infocollect.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.swing.text.html.parser.Entity;


/**
 * 派出单位计划管理Controller
 *
 * @author infocollect
 * @date 2022-07-09
 */
@RestController
@RequestMapping("/grant/companyplan")
public class GrCompanyPlanController extends BaseController
{
    @Autowired
    private IGrCompanyPlanService grCompanyPlanService;
    @Autowired
    private  IGrGrantService grantService;
    @Autowired
    private IGrGranttypeService granttypeService;
    @Autowired
    private IGrFamiliesService familiesService;
    @Autowired
    private IGrCompanyService companyService;
    @Autowired
    private IGrUserCompanyService userCompanyService;

    /**
     * 查询派出单位计划管理列表
     */
    @PreAuthorize("@ss.hasPermi('grant:companyplan:list')")
    @GetMapping("/list")
    public TableDataInfo list(GrCompanyPlan grCompanyPlan)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        if(SecurityUtils.isInfocollectAdmin(userId)) {
            //如果是管理员，走管理员单独的统计逻辑
            grCompanyPlan.setLvl(2);
        }else {
            GrUserCompany userCompany = new GrUserCompany();
            userCompany.setUserId(userId);
            userCompany.setGrantId(grCompanyPlan.getGrantId());
            List<GrUserCompany> userCompanyList =  userCompanyService.selectGrUserCompanyList(userCompany);
            if(userCompanyList.size()>0){
                userCompany = userCompanyList.get(0);
            }
            grCompanyPlan.setLvl(3);
            grCompanyPlan.setSubjectCodeArr(getPlanSubjects(grCompanyPlan,userCompany));
            if(2==userCompany.getLvl()){
                grCompanyPlan.setParentId(userCompany.getCompanyId());
            }else {
                grCompanyPlan.setCompanyId(userCompany.getCompanyId());
            }
        }

//        startPage();
        List<GrCompanyPlan> list = grCompanyPlanService.selectGrCompanyPlanList(grCompanyPlan);
        return getDataTable(list);
    }
    private List<Long> getPlanSubjects(GrCompanyPlan grCompanyPlan,GrUserCompany userCompany){
        List<Long> subjectCodeArr = new ArrayList<>();
        GrCompanyPlan grCompanyPlanSubject = new GrCompanyPlan();
        BeanUtils.copyProperties(grCompanyPlan,grCompanyPlanSubject);
        grCompanyPlanSubject.setCompanyId(userCompany.getCompanyId());
        grCompanyPlanSubject.setLvl(userCompany.getLvl());
        List<GrCompanyPlan> list = grCompanyPlanService.selectGrCompanyPlanList(grCompanyPlanSubject);
        for(int row=0;row<list.size();row++){
            GrCompanyPlan grCompanyPlan1 = list.get(row);
            if(grCompanyPlan1.getPlanNum()>0){
                subjectCodeArr.add(grCompanyPlan1.getSubjectCode());
            }
        }
        return subjectCodeArr;
    }
    /**
     * 派出单位查看自己的计划
     * @param grCompanyPlan
     * @return
     */
    @GetMapping("/listSelfPlan")
    public TableDataInfo listSelfPlan(GrCompanyPlan grCompanyPlan)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        if(SecurityUtils.isInfocollectAdmin(userId)) {
            //如果是管理员，走管理员单独的统计逻辑
            grCompanyPlan.setLvl(2);
        }else {
            GrUserCompany userCompany = new GrUserCompany();
            userCompany.setUserId(userId);
            userCompany.setGrantId(grCompanyPlan.getGrantId());
            List<GrUserCompany> userCompanyList =  userCompanyService.selectGrUserCompanyList(userCompany);
            if(userCompanyList.size()>0){
                userCompany = userCompanyList.get(0);
            }
            grCompanyPlan.setSubjectCodeArr(getPlanSubjects(grCompanyPlan,userCompany));
                grCompanyPlan.setCompanyId(userCompany.getCompanyId());
        }

//        startPage();
        List<GrCompanyPlan> list = grCompanyPlanService.selectGrCompanyPlanList(grCompanyPlan);
        return getDataTable(list);
    }
    /**
     * 导出派出单位计划管理列表
     */
    @PreAuthorize("@ss.hasPermi('grant:companyplan:export')")
    @Log(title = "派出单位计划管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(GrCompanyPlan grCompanyPlan)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        if(SecurityUtils.isInfocollectAdmin(userId)) {
            //如果是管理员，走管理员单独的统计逻辑
            grCompanyPlan.setLvl(2);
        }else {
            GrUserCompany userCompany = new GrUserCompany();
            userCompany.setUserId(userId);
            userCompany.setGrantId(grCompanyPlan.getGrantId());
            List<GrUserCompany> userCompanyList =  userCompanyService.selectGrUserCompanyList(userCompany);
            if(userCompanyList.size()>0){
                userCompany = userCompanyList.get(0);
            }
            grCompanyPlan.setLvl(3);
            if(2==userCompany.getLvl()){
                grCompanyPlan.setParentId(userCompany.getCompanyId());
            }else {
                grCompanyPlan.setCompanyId(userCompany.getCompanyId());
            }
        }
        List<GrCompanyPlan> list = grCompanyPlanService.selectGrCompanyPlanList(grCompanyPlan);
        ExcelUtil<GrCompanyPlan> util = new ExcelUtil<GrCompanyPlan>(GrCompanyPlan.class);
        return util.exportExcel(list, "companyplan");
    }

    /**
     * 获取派出单位计划管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('grant:companyplan:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(grCompanyPlanService.selectGrCompanyPlanById(id));
    }

    /**
     * 新增派出单位计划管理
     */
    @PreAuthorize("@ss.hasPermi('grant:companyplan:add')")
    @Log(title = "派出单位计划管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody GrCompanyPlan grCompanyPlan)
    {
        return toAjax(grCompanyPlanService.insertGrCompanyPlan(grCompanyPlan));
    }

    /**
     * 修改派出单位计划管理
     */
    @PreAuthorize("@ss.hasPermi('grant:companyplan:edit')")
    @Log(title = "派出单位计划管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody GrCompanyPlan grCompanyPlan)
    {
        return toAjax(grCompanyPlanService.updateGrCompanyPlan(grCompanyPlan));
    }

    /**
     * 删除派出单位计划管理
     */
    @PreAuthorize("@ss.hasPermi('grant:companyplan:remove')")
    @Log(title = "派出单位计划管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(grCompanyPlanService.deleteGrCompanyPlanByIds(ids));
    }

    /**
     * 生成派出单位计划
     * @param grCompanyPlan
     * @return
     */
    @ResponseBody
    @PostMapping("createComapnyPlan")
    public AjaxResult createComapnyPlan(@RequestBody GrCompanyPlan grCompanyPlan){
        Long grantId = grCompanyPlan.getGrantId();
        if(grantId==null){
            return AjaxResult.error("请先选择要生成计划的项目");
        }
        GrCompany grCompany= getCompanyForLogin(grantId);
        if(grCompany==null){
            return AjaxResult.error("获取派出单位错误");
        }
        Long companyId = grCompany.getId();
        //根据项目类型获取所有的科类
        //根据派出单位，获取所有的下级派出单位
        //根据下级单位，循环生成计划数
        GrGrant grant = new GrGrant();
        grant.setGrantId(grantId);
        grant = grantService.selectGrGrantById(grantId);
        Long grantTypeId = grant.getGranttypeId();
        GrFamilies families = new GrFamilies();
        families.setGranttypeId(grantTypeId);
        families.setIsEnabled("Y");
        List<GrFamilies> familiesList = familiesService.selectGrFamiliesList(families);
        familiesList.stream().forEach(familie->{
            if(familie.getParentId()==0){
                //父节点不用生成计划
                return;
            }
            GrCompany company = new GrCompany();
            company.setParentId(companyId);
            company.setIsEnabled("Y");
            List<GrCompany> companyList = companyService.selectGrCompanyList(company);
            companyList.stream().forEach(com->{
                GrCompanyPlan companyPlan = new GrCompanyPlan();
                companyPlan.setCompanyId(com.getId());
                companyPlan.setSubjectCode(familie.getId());
                companyPlan.setGrantId(grantId);
                List<GrCompanyPlan> companyPlanList = grCompanyPlanService.selectGrCompanyPlanList(companyPlan);
                if(companyPlanList.size()>0)
                {return;}
                companyPlan.setPlanNum(0);
                grCompanyPlanService.insertGrCompanyPlan(companyPlan);
            });


        });
        return AjaxResult.success();
    }
    public GrCompany getCompanyForLogin(Long grantId){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        if(SecurityUtils.isInfocollectAdmin(userId)){
            //如果是管理员，走管理员单独的统计逻辑
            GrCompany company = new GrCompany();
            company.setGrantId(grantId);
            company.setLvl(1);
            List<GrCompany> grCompanyList = companyService.selectGrCompanyList(company);
            if(grCompanyList.size()<=0){
                throw new CustomException("请先设置一级派出单位");
            }
            company = grCompanyList.get(0);  //这里是获得本次报名的顶级派出单位(一般是杭州考试院)
            return company;
        }
        GrUserCompany userCompany = new GrUserCompany();
        userCompany.setUserId(userId);
        userCompany.setGrantId(grantId);
        List<GrUserCompany> userCompanyList = userCompanyService.selectGrUserCompanyList(userCompany);
        if(userCompanyList.size()<=0){
            return null;
        }
        userCompany = userCompanyList.get(0);
        Long userCompanyId = userCompany.getCompanyId();
        GrCompany company = companyService.selectGrCompanyById(userCompanyId);
        if(company==null){
            return null;
        }
        return company;
    }
    /**
     * 导入派出单位计划
     * @param file
     * @return
     */
    @ResponseBody
    @PostMapping("importComapnyPlan")
    public AjaxResult importComapnyPlan(MultipartFile file,Long grantId) throws Exception{
        if(grantId == null){
            return AjaxResult.error("错误的项目信息！");
        }
        if(file ==null){
            return AjaxResult.error("错误的文件信息！");
        }
        ExcelUtil<GrCompanyPlan> util = new ExcelUtil<GrCompanyPlan>(GrCompanyPlan.class);
        List<GrCompanyPlan> planList = util.importExcel(file.getInputStream());
        for(int row=0,size = planList.size();row<size;row++){
            GrCompanyPlan companyPlan = planList.get(row);
            GrCompanyPlan companyPlanUpdate = new GrCompanyPlan();
            if(grantId==companyPlan.getGrantId()){
                companyPlanUpdate.setId(companyPlan.getId());
                companyPlanUpdate.setPlanNum(companyPlan.getPlanNum());
                grCompanyPlanService.updateGrCompanyPlan(companyPlanUpdate);
            }
        }
        return AjaxResult.success();
    }
    /**
     * 获取派出单位计划_根据科目横表展示
     * @param grCompanyPlan
     * @return
     */
    @GetMapping("/getCompanyPlanForSubject")
    public AjaxResult getCompanyPlanForSubject(GrCompanyPlan grCompanyPlan){
        TableDataInfo planTable = list(grCompanyPlan);
        List<GrCompanyPlan> companyPlanList = (List<GrCompanyPlan> )planTable.getRows();
        Map<Long,String> subjectMap = new HashMap();
        for(int row=0;row<companyPlanList.size();row++){
            //计算总共哪些科类有计划数
            subjectMap.put(companyPlanList.get(row).getSubjectCode(),"Y");
        }

        Long grantId = grCompanyPlan.getGrantId();
        GrCompany grCompany= getCompanyForLogin(grantId);
        Long companyId = grCompany.getId();
        //根据项目类型获取所有的科类
        GrGrant grant = new GrGrant();
        grant.setGrantId(grantId);
        grant = grantService.selectGrGrantById(grantId);
        Long grantTypeId = grant.getGranttypeId();


        List<PlanFieldDto> fieldMapList = new ArrayList<>();
        PlanFieldDto comPlanFieldDto = new PlanFieldDto();
        comPlanFieldDto.setKey("comId");
        comPlanFieldDto.setValue("派出单位ID");
        fieldMapList.add(comPlanFieldDto);

        comPlanFieldDto = new PlanFieldDto();
        comPlanFieldDto.setKey("comName");
        comPlanFieldDto.setValue("派出单位");
        fieldMapList.add(comPlanFieldDto);

        GrFamilies families = new GrFamilies();
        families.setGranttypeId(grantTypeId);
        families.setIsEnabled("Y");
        List<GrFamilies> familiesList = familiesService.selectGrFamiliesList(families);
        familiesList.stream().forEach(familie->{
            if(familie.getParentId()==0){
                return;
            }
            if(!"Y".equals(subjectMap.get(familie.getId()))){
                //没有计划数的不展示
                return;
            }
            PlanFieldDto planFieldDto = new PlanFieldDto();
            planFieldDto.setKey(String.valueOf(familie.getId()));
            planFieldDto.setValue(familie.getFamiliesName());
            fieldMapList.add(planFieldDto);
            planFieldDto = new PlanFieldDto();
            if(!"Y".equals(grCompanyPlan.getIsExportTemplate())) {
                //导出模版的时候，就不用加上报名数了
                planFieldDto.setKey("enroll" + String.valueOf(familie.getId()));
                planFieldDto.setValue(familie.getFamiliesName() + "报名数");
                fieldMapList.add(planFieldDto);
            }
        });
        PlanFieldDto planFieldDto = new PlanFieldDto();
        planFieldDto.setKey(String.valueOf("计划合计"));
        planFieldDto.setValue("计划合计");
        fieldMapList.add(planFieldDto);

        List<Map<String,String>> rowMapList = new ArrayList<>();
        Map<String,String> dataRowMap = new HashMap();
        Long oldCompanyId = 0l;
        Integer planSum = 0;
        for(int row=0;row<companyPlanList.size();row++){
            GrCompanyPlan grCompanyPlan1= companyPlanList.get(row);
            Long newCompanyId = grCompanyPlan1.getCompanyId();
            if(!oldCompanyId.equals(newCompanyId)){
                if(oldCompanyId != 0){
                    dataRowMap.put("计划合计",String.valueOf(planSum));
                    rowMapList.add(dataRowMap);
                    dataRowMap = new HashMap();
                    planSum = new Integer(0);
                }
                oldCompanyId = newCompanyId;
            }
            planSum += grCompanyPlan1.getPlanNum();
            dataRowMap.put(String.valueOf(grCompanyPlan1.getSubjectCode()),String.valueOf(grCompanyPlan1.getPlanNum()));
            dataRowMap.put("enroll"+String.valueOf(grCompanyPlan1.getSubjectCode()),String.valueOf(grCompanyPlan1.getEnrollNum()));
            dataRowMap.put("comName",grCompanyPlan1.getComName());
            dataRowMap.put("comId",String.valueOf(grCompanyPlan1.getCompanyId()));
        }
        dataRowMap.put("计划合计",String.valueOf(planSum));
        rowMapList.add(dataRowMap);
        JSONObject planForSubjectObj = new JSONObject();
        planForSubjectObj.put("FIELDMAP",fieldMapList);
        planForSubjectObj.put("ROWMAPLIST",rowMapList);
        return AjaxResult.success(planForSubjectObj);
    }
    /**
     * 获取派出单位计划_根据科目横表展示_本单位
     * @param grCompanyPlan
     * @return
     */
    @GetMapping("/getCompanyPlanForSubjectSelf")
    public AjaxResult getCompanyPlanForSubjectSelf(GrCompanyPlan grCompanyPlan){
        TableDataInfo planTable = listSelfPlan(grCompanyPlan);
        List<GrCompanyPlan> companyPlanList = (List<GrCompanyPlan> )planTable.getRows();
        Map<Long,String> subjectMap = new HashMap();
        for(int row=0;row<companyPlanList.size();row++){
            //计算总共哪些科类有计划数
            subjectMap.put(companyPlanList.get(row).getSubjectCode(),"Y");
        }
        Long grantId = grCompanyPlan.getGrantId();
        GrCompany grCompany= getCompanyForLogin(grantId);
        Long companyId = grCompany.getId();
        //根据项目类型获取所有的科类
        GrGrant grant = new GrGrant();
        grant.setGrantId(grantId);
        grant = grantService.selectGrGrantById(grantId);
        Long grantTypeId = grant.getGranttypeId();

        List<PlanFieldDto> fieldMapList = new ArrayList<>();
        PlanFieldDto comPlanFieldDto = new PlanFieldDto();
        comPlanFieldDto.setKey("comId");
        comPlanFieldDto.setValue("派出单位ID");
        fieldMapList.add(comPlanFieldDto);

        comPlanFieldDto = new PlanFieldDto();
        comPlanFieldDto.setKey("comName");
        comPlanFieldDto.setValue("派出单位");
        fieldMapList.add(comPlanFieldDto);

        GrFamilies families = new GrFamilies();
        families.setGranttypeId(grantTypeId);
        families.setIsEnabled("Y");
        List<GrFamilies> familiesList = familiesService.selectGrFamiliesList(families);
        familiesList.stream().forEach(familie->{
            if(familie.getParentId()==0){
                return;
            }
            if(!"Y".equals(subjectMap.get(familie.getId()))){
                //没有计划数的不展示
                return;
            }
            PlanFieldDto planFieldDto = new PlanFieldDto();
            planFieldDto.setKey(String.valueOf(familie.getId()));
            planFieldDto.setValue(familie.getFamiliesName());
            fieldMapList.add(planFieldDto);
//            planFieldDto = new PlanFieldDto();
//            planFieldDto.setKey("enroll"+String.valueOf(familie.getId()));
//            planFieldDto.setValue(familie.getFamiliesName()+"报名数");
//            fieldMapList.add(planFieldDto);
        });
        List<Map<String,String>> rowMapList = new ArrayList<>();
        Map<String,String> dataRowMap = new HashMap();
        Long oldCompanyId = 0l;
        for(int row=0;row<companyPlanList.size();row++){
            GrCompanyPlan grCompanyPlan1= companyPlanList.get(row);
            Long newCompanyId = grCompanyPlan1.getCompanyId();
            if(!oldCompanyId.equals(newCompanyId)){
                if(oldCompanyId != 0){
                    rowMapList.add(dataRowMap);
                    dataRowMap = new HashMap();
                }
                oldCompanyId = newCompanyId;
            }
            dataRowMap.put(String.valueOf(grCompanyPlan1.getSubjectCode()),String.valueOf(grCompanyPlan1.getPlanNum()));
            dataRowMap.put("enroll"+String.valueOf(grCompanyPlan1.getSubjectCode()),String.valueOf(grCompanyPlan1.getEnrollNum()));
            dataRowMap.put("comName",grCompanyPlan1.getComName());
            dataRowMap.put("comId",String.valueOf(grCompanyPlan1.getCompanyId()));
        }
        rowMapList.add(dataRowMap);
        JSONObject planForSubjectObj = new JSONObject();
        planForSubjectObj.put("FIELDMAP",fieldMapList);
        planForSubjectObj.put("ROWMAPLIST",rowMapList);
        return AjaxResult.success(planForSubjectObj);
    }
    /**
     * 获取派出单位计划_根据科目横表展示
     */
    @Log(title = "获取派出单位计划_根据科目横表展示", businessType = BusinessType.EXPORT)
    @GetMapping("/exportForSubject")
    public AjaxResult exportForSubject(GrCompanyPlan grCompanyPlan)
    {
        AjaxResult dataResult = getCompanyPlanForSubject(grCompanyPlan);
        JSONObject planForSubjectObj = (JSONObject)dataResult.get("data");
        List<String> configshowcels = Arrays.asList(grCompanyPlan.getConfigshowcelSearch().split(","));
        List<PlanFieldDto> fieldMapList = (List<PlanFieldDto>)planForSubjectObj.get("FIELDMAP");
        List<PlanFieldDto> fieldMapListExport = new ArrayList<>();
        for(int row=0;row<fieldMapList.size();row++){
            if(configshowcels.contains(fieldMapList.get(row).getKey())){
                fieldMapListExport.add(fieldMapList.get(row));
            }
        }
        List<Map<String,String>> rowMapList = (List<Map<String,String>>)planForSubjectObj.get("ROWMAPLIST");
        ExcelCustomUtil excelCustomUtil = new ExcelCustomUtil();
        return excelCustomUtil.exportExcel(fieldMapListExport,rowMapList,"派出单位科类计划");
    }
    /**
     * 获取派出单位计划_根据科目横表展示
     */
    @Log(title = "导出派出单位计划数", businessType = BusinessType.EXPORT)
    @GetMapping("/exportPlanForSubject")
    public AjaxResult exportPlanForSubject(GrCompanyPlan grCompanyPlan)
    {
        TableDataInfo planTable = listSelfPlan(grCompanyPlan);
        List<GrCompanyPlan> companyPlanList = (List<GrCompanyPlan> )planTable.getRows();
        Map<Long,String> subjectMap = new HashMap();
        for(int row=0;row<companyPlanList.size();row++){
            //计算总共哪些科类有计划数
            subjectMap.put(companyPlanList.get(row).getSubjectCode(),"Y");
        }
        Long grantId = grCompanyPlan.getGrantId();
        GrCompany grCompany= getCompanyForLogin(grantId);
        Long companyId = grCompany.getId();
        //根据项目类型获取所有的科类
        GrGrant grant = new GrGrant();
        grant.setGrantId(grantId);
        grant = grantService.selectGrGrantById(grantId);
        Long grantTypeId = grant.getGranttypeId();

        List<PlanFieldDto> fieldMapList = new ArrayList<>();
        PlanFieldDto comPlanFieldDto = new PlanFieldDto();
        comPlanFieldDto.setKey("comId");
        comPlanFieldDto.setValue("派出单位ID");
        fieldMapList.add(comPlanFieldDto);

        comPlanFieldDto = new PlanFieldDto();
        comPlanFieldDto.setKey("comName");
        comPlanFieldDto.setValue("派出单位");
        fieldMapList.add(comPlanFieldDto);

        GrFamilies families = new GrFamilies();
        families.setGranttypeId(grantTypeId);
        families.setIsEnabled("Y");
        List<GrFamilies> familiesList = familiesService.selectGrFamiliesList(families);
        familiesList.stream().forEach(familie->{
            if(familie.getParentId()==0){
                return;
            }
            if(!"Y".equals(subjectMap.get(familie.getId()))){
                //没有计划数的不展示
                return;
            }
            PlanFieldDto planFieldDto = new PlanFieldDto();
            planFieldDto.setKey(String.valueOf(familie.getId()));
            planFieldDto.setValue(familie.getFamiliesName());
            fieldMapList.add(planFieldDto);
//            planFieldDto = new PlanFieldDto();
//            planFieldDto.setKey("enroll"+String.valueOf(familie.getId()));
//            planFieldDto.setValue(familie.getFamiliesName()+"报名数");
//            fieldMapList.add(planFieldDto);
        });
        List<Map<String,String>> rowMapList = new ArrayList<>();
        Map<String,String> dataRowMap = new HashMap();
        Long oldCompanyId = 0l;
        for(int row=0;row<companyPlanList.size();row++){
            GrCompanyPlan grCompanyPlan1= companyPlanList.get(row);
            Long newCompanyId = grCompanyPlan1.getCompanyId();
            if(!oldCompanyId.equals(newCompanyId)){
                if(oldCompanyId != 0){
                    rowMapList.add(dataRowMap);
                    dataRowMap = new HashMap();
                }
                oldCompanyId = newCompanyId;
            }
            dataRowMap.put(String.valueOf(grCompanyPlan1.getSubjectCode()),String.valueOf(grCompanyPlan1.getPlanNum()));
            dataRowMap.put("enroll"+String.valueOf(grCompanyPlan1.getSubjectCode()),String.valueOf(grCompanyPlan1.getEnrollNum()));
            dataRowMap.put("comName",grCompanyPlan1.getComName());
            dataRowMap.put("comId",String.valueOf(grCompanyPlan1.getCompanyId()));
        }
        rowMapList.add(dataRowMap);

        List<String> configshowcels = Arrays.asList(grCompanyPlan.getConfigshowcelSearch().split(","));
        List<PlanFieldDto> fieldMapListExport = new ArrayList<>();
        for(int row=0;row<fieldMapList.size();row++){
            if(configshowcels.contains(fieldMapList.get(row).getKey())){
                fieldMapListExport.add(fieldMapList.get(row));
            }
        }
        ExcelCustomUtil excelCustomUtil = new ExcelCustomUtil();
        return excelCustomUtil.exportExcel(fieldMapListExport,rowMapList,"本单位科类派出计划");
    }
    /**
     * 导入派出单位计划_横表导入
     * @param file
     * @return
     */
    @ResponseBody
    @PostMapping("importComapnyPlanForSubject")
    public AjaxResult importComapnyPlanForSubject(MultipartFile file,Long grantId) throws Exception{
        if(grantId == null){
            return AjaxResult.error("错误的项目信息！");
        }
        if(file ==null){
            return AjaxResult.error("错误的文件信息！");
        }
        ExcelCustomUtil excelCustomUtil = new ExcelCustomUtil();
        List<Map<String,Object>> dataList = excelCustomUtil.importExcel(file.getInputStream());


        GrCompany grCompany= getCompanyForLogin(grantId);
        Long companyId = grCompany.getId();
        //根据项目类型获取所有的科类
        GrGrant grant = new GrGrant();
        grant.setGrantId(grantId);
        grant = grantService.selectGrGrantById(grantId);
        Long grantTypeId = grant.getGranttypeId();
        GrFamilies families = new GrFamilies();
        families.setGranttypeId(grantTypeId);
        families.setIsEnabled("Y");
        List<GrFamilies> familiesList = familiesService.selectGrFamiliesList(families);
        Map<String,String> fieldMap = new HashMap<>();
        familiesList.stream().forEach(grfamilies->{
            if(grfamilies.getParentId()==0){
                return;
            }
            fieldMap.put(grfamilies.getFamiliesName(),String.valueOf(grfamilies.getId()));
        });
        dataList.stream().forEach(planData->{
            Long importComId = Long.valueOf((String)planData.get("派出单位ID"));
            for(Map.Entry entry: fieldMap.entrySet()){
                String subjectName= (String)entry.getKey();
                String subjectId = (String)entry.getValue();
                String plan = (String)planData.get(subjectName);
                if(plan ==null){
                    continue;
                }
                GrCompanyPlan findPlan = new GrCompanyPlan();
                findPlan.setCompanyId(importComId);
                findPlan.setGrantId(grantId);
                findPlan.setSubjectCode(Long.valueOf(subjectId));
                List<GrCompanyPlan> companyPlanList= grCompanyPlanService.selectGrCompanyPlanList(findPlan);
                if(companyPlanList.size()>0){
                    GrCompanyPlan companyPlanUpdate = companyPlanList.get(0);
                    companyPlanUpdate.setPlanNum(Integer.valueOf(plan));
                    grCompanyPlanService.updateGrCompanyPlan(companyPlanUpdate);
                }
            }
        });
        return checkCompanyPlan(companyId,grantId);
    }

    /**
     * 检查本单位计划数与下级单位计划数是否匹配
     * @param companyId
     * @return
     */
    private AjaxResult checkCompanyPlan(Long companyId,Long grantId){
        GrCompanyPlan checkPlan = new GrCompanyPlan();
        checkPlan.setCompanyId(companyId);
        checkPlan.setGrantId(grantId);
        String checkResultMsg = "";
        List<GrCompanyPlan> checkPlanList= grCompanyPlanService.selectGrCompanyPlanList(checkPlan);
        for(int row=0;row<checkPlanList.size();row++){
            checkPlan = checkPlanList.get(row);
            Integer plan = checkPlan.getPlanNum();
            GrCompanyPlan subjectCheckPlan = new GrCompanyPlan();
            subjectCheckPlan.setParentId(companyId);
            subjectCheckPlan.setGrantId(grantId);
            subjectCheckPlan.setSubjectCode(checkPlan.getSubjectCode());
            List<GrCompanyPlan> subjectCheckPlanList= grCompanyPlanService.selectGrCompanyPlanList(subjectCheckPlan);
            Integer subjectPlan = 0;
            for(int srow=0;srow<subjectCheckPlanList.size();srow++){
                subjectPlan += subjectCheckPlanList.get(srow).getPlanNum();
            }
            if(plan != subjectPlan){
                checkResultMsg += StringUtils.rightPad(checkPlan.getFamiliesName()+"计划："+plan,30)+";导入计划合计:"+subjectPlan+"</br>";
            }
            logger.info("科目计划数：{}",checkPlan.toString());
        }

        return AjaxResult.success(checkResultMsg);
    }
    /**
     * 删除派出单位计划
     * @param file
     * @return
     */
    @ResponseBody
    @PostMapping("deleteGrCompanyPlanByComId")
    public AjaxResult deleteGrCompanyPlanByComId(@RequestBody GrCompanyPlan grCompanyPlan){
        Long grantId = grCompanyPlan.getGrantId();
        if(grantId==null){
            return AjaxResult.error("请先选择要生成计划的项目");
        }
        GrCompany grCompany= getCompanyForLogin(grantId);
        if(grCompany==null){
            return AjaxResult.error("获取派出单位错误");
        }
        grCompanyPlan.setCompanyId(grCompany.getId());
        Long companyId = grCompany.getId();
        GrCompany company = new GrCompany();
        company.setParentId(companyId);
        company.setIsEnabled("Y");
        List<GrCompany> companyList = companyService.selectGrCompanyList(company);
        companyList.stream().forEach(com->{
            grCompanyPlan.setCompanyId(com.getId());
            grCompanyPlanService.deleteGrCompanyPlanByComId(grCompanyPlan);
        });

        return AjaxResult.success();
    }
}
